<?php


namespace app\admin\model;

use app\common\gateway\data\Data;
use app\common\gateway\data\Sender;
use app\common\gateway\data\UserSender;
use support\Model;

class Admin extends Model
{

    protected $fillable = ['username', 'nickname', 'password', 'salt', 'email', 'loginfailure', 'logintime', 'loginip', 'status', 'avatar'];

    protected $visible = [
        'id',
        'username',
        'nickname',
        'email',
        'loginfailure',
        'logintime',
        'loginip',
        'avatar',
        'status'
    ];

    /**
     * @var Sender
     */
    protected $gatewaySender = null;

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'admin_role_access', 'admin_id', 'role_id');
    }

    public static function getStatusList()
    {
        return ['normal' => '正常', 'disibled' => '禁用'];
    }

    /**
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @param array $where
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch($query, $where = [])
    {
        if (isset($where['nickname'])) {
            $query->where('nickname', 'like', '%' . $where['nickname'] . '%');
        }
        if (isset($where['email'])) {
            $query->where('email', 'like', '%' . $where['email'] . '%');
        }
        return $query;
    }

    public function getSender() {
        if ($this->gatewaySender === null) {
            $this->gatewaySender = new UserSender($this->id);
        }
        return $this->gatewaySender;
    }

    public function sendMsg(Data $data) {
        $this->getSender()->send($data);
    }
}
